/**
 * 账户登陆界面
 * @author William
 * 2012-5-10
 */
package com.ytu.clouddisk.face;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ytu.clouddisk.kanbox.KanBoxControl;
import com.ytu.clouddisk.utils.LoginUtil;
import com.ytu.clouddisk.utils.Varibles;

public class CloudDiskLoginActivity extends Activity {

	private ExpandableListView expandableListView;
	private Button btnOK;
	private Button btnExit;
	private static ProgressDialog dlg_refresh;
	private OnClickListener listenerBtn;
	private SharedPreferences sp;
	private ExListAdapter adapter;
	// 表示是否登陆
	private boolean isGoogleLogin = false;
	private boolean isVDiskLogin = false;
	private boolean isKanBoxLogin = false;
	private boolean isKuaiPanLogin = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		init();
	}

	/**
	 * 清理账户配置文件
	 * 
	 * @param bg
	 *            表示是否记住google账户，若是为真
	 * @param bv
	 *            表示是否记住VDISK账户，若是为真
	 */
	protected void clearCfg(boolean bg, boolean bv) {
		if (sp == null)
			sp = getSharedPreferences(Varibles.CONFIG_FILE, MODE_PRIVATE);
		if (!bg && !bv)
			sp.edit().clear().commit();
		else {
			sp.edit().remove(Varibles.KANBOX_ACCESS_TOKEN).commit();
			sp.edit().remove(Varibles.GOOGLE_TOKEN).commit();
			sp.edit().remove(Varibles.VDISK_TOKEN).commit();
			if (!bg) { // 如果没记住google账户
				sp.edit().remove(Varibles.GOOGLE_ACCOUNT + "User").commit();
				sp.edit().remove(Varibles.GOOGLE_ACCOUNT + "Psd").commit();
			}
			if (!bv) { // 如果没记住vdisk账户
				sp.edit().remove(Varibles.VDISK_ACCOUNT + "User").commit();
				sp.edit().remove(Varibles.VDISK_ACCOUNT + "Psd").commit();
			}
		}
	}

	/**
	 * 检测账户是否配置
	 * 
	 * @param user
	 * @param psd
	 * @return
	 */
	private boolean checkAccount(String user, String psd) {
		return getSharedPreferences(Varibles.CONFIG_FILE, MODE_PRIVATE)
				.contains(user)
				&& getSharedPreferences(Varibles.CONFIG_FILE, MODE_PRIVATE)
						.contains(psd);
	}

	/**
	 * 初始化
	 */
	protected void init() {
		expandableListView = (ExpandableListView) findViewById(R.id.expandlistview);
		btnOK = (Button) findViewById(R.id.btn_ok);
		btnExit = (Button) findViewById(R.id.btn_exit);

		listenerBtn = new Button.OnClickListener() {

			@Override
			public void onClick(View v) {

				if (v.equals(btnOK)) {
					Intent intent = new Intent(CloudDiskLoginActivity.this,
							BrowserActivity.class);
					startActivity(intent);
				} else if (v.equals(btnExit)) {
					clearCfg(false, false);
					finish();
				}
			}

		};

		btnOK.setOnClickListener(listenerBtn);
		btnExit.setOnClickListener(listenerBtn);
		sp = getSharedPreferences(Varibles.CONFIG_FILE, MODE_PRIVATE);
		adapter = new ExListAdapter(this);
		expandableListView.setAdapter(adapter);
		expandableListView
				.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

					@Override
					public boolean onChildClick(ExpandableListView parent,
							View v, int groupPosition, int childPosition,
							long id) {
						if (groupPosition == 0) {
							switch (childPosition) {
							case 0: { // Drive
								// 多线程
								if (!checkAccount(Varibles.GOOGLE_ACCOUNT
										+ "User", // 包含就返回真
										Varibles.GOOGLE_ACCOUNT + "Psd")) {
									Toast.makeText(CloudDiskLoginActivity.this,
											"请先配置账户", Toast.LENGTH_SHORT)
											.show();
									break;
								} else {
									dlg_refresh = ProgressDialog.show(
											CloudDiskLoginActivity.this,
											"Please waiting...", "Docs登录中...",
											true);
									new LoginThread(Varibles.GOOGLEDOCS)
											.start();
								}
								break;
							}
							case 1: {
								if (!checkAccount(Varibles.VDISK_ACCOUNT
										+ "User", // 包含就返回真
										Varibles.VDISK_ACCOUNT + "Psd")) {
									Toast.makeText(CloudDiskLoginActivity.this,
											"请先配置账户", Toast.LENGTH_SHORT)
											.show();
									break;
								} else {
									dlg_refresh = ProgressDialog.show(
											CloudDiskLoginActivity.this,
											"Please waiting...", "VDisk登录中...",
											true);
									new LoginThread(Varibles.VDISK).start();
								}
							}
							}
						} else if (groupPosition == 1) {
							switch (childPosition) {
							case 0: {
								KanBoxControl.getInstance(
										CloudDiskLoginActivity.this).getOauth();
								break;
							}
							case 1: {
								Toast.makeText(CloudDiskLoginActivity.this,
										"暂未实现", Toast.LENGTH_SHORT).show();
								break;
							}
							}
						} else if (groupPosition == 2) {
							switch (childPosition) {
							case 0: {
								Intent intent = new Intent(
										CloudDiskLoginActivity.this,
										AccountConfigActivity.class);
								intent.putExtra("keyCode",
										Varibles.GOOGLE_REQUEST_CODE);
								startActivityForResult(intent,
										Varibles.REQUEST_CODE); // 启动设置页面
								break;
							}
							case 1: {
								Intent intent = new Intent(
										CloudDiskLoginActivity.this,
										AccountConfigActivity.class);
								intent.putExtra("keyCode",
										Varibles.VDISK_REQUEST_CODE);
								startActivityForResult(intent,
										Varibles.REQUEST_CODE); // 启动设置页面
								break;
							}
							case 2: {// about me
								break;
							}
							}
						}
						return false;
					}
				});
	}

	/**
	 * 内部适配器类
	 */
	class ExListAdapter extends BaseExpandableListAdapter {

		Context context;
		LayoutInflater mlayoutInflater;
		String[] parent = { "客户端登陆", "网页登陆", "账户配置" };
		String[][] child = { { "Google Drive", "新浪微盘" }, { "酷盘", "快盘" },
				{ "Google Drive", "新浪微盘", "About Me" } };

		ExListAdapter(Context context) {
			this.context = context;
			mlayoutInflater = LayoutInflater.from(context);
		}

		@Override
		public Object getChild(int groupPosition, int childPosition) {

			return this.child[groupPosition][childPosition];
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {

			return childPosition;
		}

		// 子列
		@Override
		public View getChildView(int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent) {
			convertView = mlayoutInflater.inflate(R.layout.childview, null);
			TextView tv = (TextView) convertView
					.findViewById(R.id.service_name);
			tv.setText(this.getChild(groupPosition, childPosition).toString());
			return convertView;
		}

		@Override
		public int getChildrenCount(int groupPosition) {
			return child[groupPosition].length;
		}

		@Override
		public Object getGroup(int groupPosition) {
			return parent[groupPosition];
		}

		@Override
		public int getGroupCount() {
			return parent.length;
		}

		@Override
		public long getGroupId(int groupPosition) {
			return groupPosition;
		}

		// 父列
		@Override
		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {
			convertView = mlayoutInflater.inflate(R.layout.parentview, null);
			TextView textParent = (TextView) convertView
					.findViewById(R.id.tv_parentview);
			textParent.setText(this.getGroup(groupPosition).toString());
			return convertView;
		}

		@Override
		public boolean hasStableIds() {

			return false;
		}

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			return true;
		}

	}

	/**
	 * 检索线程
	 * 
	 * @author William
	 * 
	 */
	class LoginThread extends Thread {
		int flag;
		Handler cloudHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				dlg_refresh.dismiss();
				if (isGoogleLogin) {
					Toast.makeText(CloudDiskLoginActivity.this, "登陆成功",
							Toast.LENGTH_SHORT).show();
					return;
				} else if (isVDiskLogin) {
					Toast.makeText(CloudDiskLoginActivity.this, "登陆成功",
							Toast.LENGTH_SHORT).show();
					return;
				} else {
					Toast.makeText(CloudDiskLoginActivity.this, "登陆失败",
							Toast.LENGTH_SHORT).show();
				}
			}
		};

		public LoginThread(int m) {
			flag = m;
		}

		public void run() {
			try {
				switch (flag) {
				case Varibles.GOOGLEDOCS:
					// 获取google token
					isGoogleLogin = LoginUtil.GoogleLogin(
							CloudDiskLoginActivity.this, sp.getString(
									Varibles.GOOGLE_ACCOUNT + "User", null), sp
									.getString(Varibles.GOOGLE_ACCOUNT + "Psd",
											null));
					break;
				case Varibles.VDISK:
					isVDiskLogin = LoginUtil
							.VDiskLogin(CloudDiskLoginActivity.this, sp
									.getString(Varibles.VDISK_ACCOUNT + "User",
											null), sp.getString(
									Varibles.VDISK_ACCOUNT + "Psd", null));
					break;
				default:
					break;
				}

			} catch (Exception e) {
				Toast.makeText(CloudDiskLoginActivity.this, "程序错误",
						Toast.LENGTH_SHORT).show();
				// finish();
			} finally {
				cloudHandler.sendEmptyMessage(0);
			}
		}
	}// end thread

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent in) {
		if (requestCode == Varibles.REQUEST_CODE) {
			if (resultCode == Varibles.GOOGLE_REQUEST_CODE) {
				Bundle bundle = in.getExtras();
				if (bundle != null) {
					if (bundle.getBoolean("result")) {
						Toast.makeText(CloudDiskLoginActivity.this, "设置成功",
								Toast.LENGTH_SHORT).show();
						return;
					} else {
						Toast.makeText(CloudDiskLoginActivity.this, "设置失败",
								Toast.LENGTH_SHORT).show();
						return;
					}
				} else {
					Toast.makeText(CloudDiskLoginActivity.this, "设置失败",
							Toast.LENGTH_SHORT).show();
					return;
				}

			} else if (resultCode == Varibles.VDISK_REQUEST_CODE) {
				Bundle bundle = in.getExtras();
				if (bundle != null) {
					if (bundle.getBoolean("result")) {
						Toast.makeText(CloudDiskLoginActivity.this, "设置成功",
								Toast.LENGTH_SHORT).show();
						return;
					} else {
						Toast.makeText(CloudDiskLoginActivity.this, "设置失败",
								Toast.LENGTH_SHORT).show();
						return;
					}
				} else {
					Toast.makeText(CloudDiskLoginActivity.this, "设置失败",
							Toast.LENGTH_SHORT).show();
					return;
				}
			} else {
				Toast.makeText(CloudDiskLoginActivity.this, "设置失败",
						Toast.LENGTH_SHORT).show();
				return;
			}
		} else {
			Toast.makeText(CloudDiskLoginActivity.this, "设置失败",
					Toast.LENGTH_SHORT).show();
			return;
		}
	}
}